package com.inputabc.ct.v1.util;

import com.inputabc.ct.v1.context.ContextParams;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Google翻译
 *
 * @author https://betheme.net/news/txtlist_i148703v.html?action=onClick
 */
public class GoogleUtils {
    //    public static void main(String[] args) throws Exception {
//        String translate = translate("こんばんは", "auto", "zh-CN");
//        System.out.printf(translate);
//    }
    
    // Google API密钥
    public static String API_KEY = "";
    
    public static final String CHINESE = "zh-CN";
    public static final String ENGLISH = "en";
    public static final String JPANESE = "ja";
    public static final String KOREAN = "ko";
    public static final String AUTO = "auto";

    public static String translate(String query, String from, String to) throws Exception {
        return getResponse("http://translate.google.com/translate_a/single", from, to, token(query), query);
    }

    public static String getResponse(String baseUrl, String from, String to, String tk, String translateText) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        params.put("client", "webapp");
        params.put("sl", from);
        params.put("tl", to);
        params.put("hl", "zh-CN");
        params.put("dt", "at");
        params.put("dt", "bd");
        params.put("dt", "ex");
        params.put("dt", "ld");
        params.put("dt", "md");
        params.put("dt", "qca");
        params.put("dt", "rw");
        params.put("dt", "rm");
        params.put("dt", "ss");
        params.put("dt", "t");
        params.put("source", "bh");
        params.put("ssel", "0");
        params.put("tsel", "0");
        params.put("kc", "1");
        params.put("tk", tk);
        params.put("q", translateText);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uri = new URIBuilder(baseUrl);
        for (String key : params.keySet()) {
            String value = params.get(key);
            uri.addParameter(key, value);
        }
        HttpUriRequest request = new HttpGet(uri.toString());
        //设置user-agent
        request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
        CloseableHttpResponse response = httpClient.execute(request);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        result = result.substring(result.indexOf("\"") + 1, result.indexOf(",") - 1);
        EntityUtils.consume(entity);
        response.getEntity().getContent().close();
        response.close();
        return result;
    }

    //调用js返回tk参数
    private static String token(String value) {
        String result = "";
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        try {
            InputStream is = ContextParams.class.getResourceAsStream("/icon/g.js");
            InputStreamReader reader = new InputStreamReader(is);
            engine.eval(reader);
            if (engine instanceof Invocable) {
                Invocable invoke = (Invocable) engine;
                result = String.valueOf(invoke.invokeFunction("token", value));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}